<template>
  <!-- 头部 -->
  <div class="header">
    <Breadcrumb></Breadcrumb>
    <div class="form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="预定编号">
          <el-input v-model="formInline.name" placeholder="预定编号" clearable />
        </el-form-item>
        <el-form-item label="预定时间">
          <el-date-picker v-model="formInline.date" type="date" placeholder="选择时间" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search">查询</el-button>
          <el-button type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="group">
      <el-button type="warning" @click="orderCollect">订单汇总</el-button>
      <el-button type="warning" @click="download">订单导出</el-button>
      <!-- <download-excel style="display:inline-block;margin-left:10px;" :data="DetailsForm" :fields="json_fields"
        :header="title" :name="title">
        <el-button class="order-btn" type="warning" @click="download">订单导出</el-button>

      </download-excel> -->
    </div>
  </div>
  <!-- 表格 -->
  <div class="content">
    <el-table :data="tableData" border style="width: 100%" header-row-class-name="active-header" @select="getselectdata"
      id="table">
      <el-table-column type="selection" width="55" :selectable="selectable" />
      <el-table-column prop="code" label="订单编号">
        <template #default="scope">
          <span style="color:blue; cursor: pointer;" @click="OrderDec(scope.row)">{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="ordername" label="下单人">
      </el-table-column>
      <el-table-column prop="company" label="所属单位">
      </el-table-column>
      <el-table-column prop="phone" label="联系电话">
      </el-table-column>
      <el-table-column label="预定时间">
        <template #default="scope">
          <span>{{ dayjs(scope.row.yudingTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="订单总价格">
      </el-table-column>
      <el-table-column label="汇总状态" prop="huizongStatus">
        <!-- <template #default="scope">
          {{ scope.row.huizongStatus == 1 ? '未汇总' : '已汇总' }}
        </template> -->
      </el-table-column>
    </el-table>
    <Pagination class="page" :total="total" :pageSize="pageSize" @CurrentChange="CurrentChange" />
  </div>
  <OrderDecs ref="child"></OrderDecs>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import OrderDecs from './OrderDecs.vue';
const router = useRouter()
//导出excel文件
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
//全局导入
const cxt = getCurrentInstance()
const API = cxt.appContext.config.globalProperties.$API
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'//全局引入时在app原型上挂载
//搜索
const formInline = reactive({
  name: '',
  date: '',
})
onMounted(() => {
  orderList()
})
//请求订单列表数据
const tableData = reactive([])
const total = ref(10)
const pageSize = ref(1)
const orderList = async (page) => {
  const result = await API.orderList({ page })
  // console.log(result);
  if (result.status == 200) {
    let arr = result.data;
    arr.forEach(ele => {
      ele.huizongStatus = ele.huizongStatus == 1 ? '未汇总' : "已汇总"
    })
    tableData.splice(0, tableData.length);
    tableData.push(...arr)
    total.value = result.total
    pageSize.value = result.pageSize
  } else {
    console.log('orderList获取失败');
    tableData.splice(0, tableData.length);
    total.value = 0
    pageSize.value = 0
  }
}
//禁用按钮-------------------------------
const selectable = (row, index) => {
  // console.log('row, index',row, index);
  // return false;
  if (row.huizongStatus == "未汇总") {
    //1 为未汇总
    return true;
  } else {
    return false;
  }
}
//处理分页器
const Current = ref('')
const CurrentChange = (page) => {
  Current.value = page
  orderList(page)
}
//点击订单汇总
const orderCollect = () => {
  //判断ids长度 至少>=2 
  if (ids.length >= 2) {
    ElMessageBox.confirm(
      '确认汇总订单吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    )
      .then(async () => {
        let result = await API.changeStatus({ ids: ids.join(',') })
        ids.splice(0, ids.length)
        // console.log(result);
        if (result.status == 200) {
          ElMessage({
            type: 'success',
            message: '汇总成功',
          })
          orderList(Current.value)
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消汇总',
        })
      })
  } else {
    ElMessageBox.alert('汇总订单至少需要2条订单信息', '汇总订单', {
      confirmButtonText: '确定',
      callback: (action) => {
        ElMessage({
          type: 'info',
          message: `取消汇总`,
        })
      },
    })
  }
}
//选中勾选内容
const ids = reactive([])
const DetailsForm = ref([])
const getselectdata = (selection, row) => {
  // console.log(selection,row);
  let arr = []
  selection.forEach(ele => {
    arr.push(ele.id)
  })
  ids.push(...arr)
  //存储当前的勾选行的数据信息------ 
  DetailsForm.value.splice(0, DetailsForm.value.length)
  DetailsForm.value.push(...selection)
}
//点击进入订单详情界面
const child = ref(null)
const OrderDec = (row) => {
  child.value.drawer = true
}
// 定义字段映射
const fieldMap = {
  "订单编号": {
    field: "code",
    callback: value => {
      return ' ' + value;
    }
  },
  "下单人": 'ordername',
  "所属单位": 'company',
  "联系电话": 'phone',
  "预定时间": 'yudingTime',
  "订单总价格": 'price',
  "汇总状态": 'huizongStatus'
};
//导出excel,导出表格=---------------
const download = () => {
  // 映射字段值
  const mappedData = DetailsForm.value.map(item => {
    const mappedItem = {};
    for (const chineseKey in fieldMap) {
      const mapping = fieldMap[chineseKey];
      if (typeof mapping === 'string') {
        mappedItem[chineseKey] = item[mapping];
      } else if (typeof mapping === 'object' && mapping.field) {
        const value = item[mapping.field];
        mappedItem[chineseKey] = mapping.callback ? mapping.callback(value) : value;
      }
    }
    return mappedItem;
  });
  // 创建工作表
  const worksheet = XLSX.utils.json_to_sheet(mappedData);
  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  // 将工作表添加到工作簿中
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  // 将工作簿转换为二进制数据
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  try {
    // 保存文件
    saveAs(new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }), '首客生鲜.xlsx');
  } catch (e) {
    console.error(e);
  }
}
</script>

<style lang="less" scoped>
.header {
  background: #fff;
  margin-bottom: 20px;
  padding: 10px;

  .demo-form-inline {
    .el-form-item {
      margin-right: 20px;
      margin-bottom: 16px;

      .el-input {
        --el-input-width: 220px;
      }
    }
  }

  .group {
    padding: 10px;
    border: 1px solid #eee;
  }
}

.content {
  background: #fff;

  :deep(.active-header) {
    color: #333
  }

  :deep(.el-table__cell) {
    text-align: center;
  }

  .page {
    padding: 20px;
  }
}
</style>